/*
** str_to_tab.c for zappy in /home/fassi_c//zappy2/zappouet/server/utils
**
** Made by clement fassi
** Login   <fassi_c@epitech.net>
**
** Started on  Wed Jun 29 12:01:21 2011 clement fassi
** Last update Wed Jun 29 12:01:23 2011 clement fassi
*/

#include <string.h>

#include "utils.h"

static int             my_strlcpy(char *dest, const char *src, int size)
{
  int           i;

  i = 0;
  while (src[i] != '\0' && i < (size - 1))
    {
      dest[i] = src[i];
      i++;
    }
  dest[i] = '\0';
  return (strlen(dest));
}

static int             word_count(const char *str, int res, const char c)
{
  int           i;
  int           inc;

  i = 0;
  inc = 1;
  if (*str == '\0')
    return (res);
  while (str[i] != c && str[i] != '\0')
    i++;
  if (i == 0)
    inc = 0;
  while (str[i] == c && str[i] != '\0')
    i++;
  return (word_count(&str[i], (res + inc), c));
}

static int            swt_fill(char **tab, const char *str, int idx,
				const char c)
{
  int           i;
  int		inc;

  i = 0;
  inc = 0;
  if (*str == '\0')
    {
      tab[idx] = NULL;
      return (-1);
    }
  while (str[i] != c && str[i] != '\0')
    i++;
  if (i > 0)
    {
      inc = 1;
      tab[idx] = xmalloc((i + 1) * sizeof(**tab));
      my_strlcpy(tab[idx], str, (i + 1));
    }
  while (str[i] == c && str[i] != '\0')
    i++;
  return (swt_fill(tab, (str + i), (idx + inc), c));
}

char            **to_word_tab(const char *str, const char c)
{
  int           nb_word;
  char          **word_tab;

  nb_word = word_count(str, 0, c);
  word_tab = xmalloc((nb_word + 1) * sizeof(*word_tab));
  swt_fill(word_tab, str, 0, c);
  return (word_tab);
}
